import React, {PureComponent} from 'react';
import {
  View,
  StyleSheet,
  Text,
  TextInput,
  Image,
  TouchableOpacity,
  TouchableWithoutFeedback,
  Keyboard,
  Modal,
} from 'react-native';
import I18n from 'react-native-i18n';
import {connect} from 'react-redux';
import BaseComponent from '../base/BaseComponent';
import {
  TextButton,
  LinearButton,
  LinearBoardButton,
} from '../../components/Button';
import {NormalHeader} from '../../components/NavigationHeader';
import {showToast} from '../../components/Toast';
import {userLogout} from '../../redux/action';
import Clipboard from '@react-native-community/clipboard';
import ModalHandler from '../../components/ModalHandler';
import WalletUtils from '../../utils/wallet/WalletUtils';
import LayoutConstants from '../../config/LayoutConstants';
import {LinerBoardTextInput} from '../../components/TextInput';
import {subNumerString} from '../../utils/tools';
import WalletConnectModal from '../../components/WalletConnectModal';

//#FFCB26
class Accept extends BaseComponent {
  constructor(props) {
    super(props);

    this.state = {
      modalVisible: false,
      loading: false,
      approved: false,
      success: false,
      gasUsed: 0,
      callFunc: '',
      showWalletConnect: false,
      tx: undefined,
    };
  }

  componentDidMount() {
    //查询授权
    let {tokenId, nftAddress} = this.props.navigation.state.params.auction;

    WalletUtils.queryNFTApproveAddress(tokenId, nftAddress).then((res) => {
      console.log('查询到授权结果');
      console.log(res);

      if (res == this.props.proxy.address) {
        this.setState({
          approved: true,
        });
      }
    });
    console.log(this.props.navigation.state.params.nft);
  }

  confirm = () => {
    Keyboard.dismiss();

    this.setState(
      {
        loading: true,
      },
      async () => {
        console.log(this.state.password);

        try {
          var privateKey = await WalletUtils.privateKeyOfKeystore(
            this.props.userInfo.keystore,
            this.state.password,
          );
        } catch (err) {
          console.log('错误' + err);
          this.setState(
            {
              modalVisible: false,
              loading: false,
            },
            () => {
              this._showAlert({content: 'invalid password'});
            },
          );
          return;
        }

        let {auction} = this.props.navigation.state.params;

        if (this.state.callFunc == 'acceptPrice') {
          WalletUtils.acceptPrice(
            privateKey,
            this.props.proxy.address,
            auction.nftAddress,
            auction.tokenId,
          )
            .then((res) => {
              console.log(res);
              this.setState({
                success: true,
              });

              setTimeout(() => {
                this.setState(
                  {
                    modalVisible: false,
                  },
                  () => {
                    this.props.navigation.state.params.refresh();
                    this.props.navigation.goBack();
                  },
                );
              }, 1000);
            })
            .catch((err) => {
              this.setState(
                {
                  modalVisible: false,
                  loading: false,
                },
                () => {
                  this._showAlert({
                    content: 'failed，please refresh and try again!',
                  });
                },
              );
            });
        } else if (this.state.callFunc == 'approve') {
          WalletUtils.approveNFT(
            privateKey,
            auction.nftAddress,
            this.props.proxy.address,
            auction.tokenId,
            (hash) => {
              this.setState({
                result: '交易已发送，正在监听交易->' + hash,
              });
            },
          )
            .then((res) => {
              console.log(res);
              this.setState({
                success: true,
                approved: true,
              });
              setTimeout(() => {
                this.setState({
                  modalVisible: false,
                  success: false,
                  loading: false,
                });
              }, 1 * 1000);
            })
            .catch((err) => {
              this.setState(
                {
                  modalVisible: false,
                  loading: false,
                },
                () => {
                  this._showAlert({content: 'failed,check your balance'});
                },
              );
            });
        } else {
          WalletUtils.agreeOutSaleAuctionBid(
            privateKey,
            this.props.proxy.address,
            auction.nftAddress,
            auction.tokenId,
          )
            .then((res) => {
              console.log(res);
              this.setState({
                success: true,
              });

              setTimeout(() => {
                this.setState(
                  {
                    modalVisible: false,
                  },
                  () => {
                    this.props.navigation.state.params.refresh();
                    this.props.navigation.goBack();
                  },
                );
              }, 2000);
            })
            .catch((err) => {
              this.setState(
                {
                  modalVisible: false,
                  loading: false,
                },
                () => {
                  this._showAlert({
                    content: 'failed，please refresh and try again!',
                  });
                },
              );
            });
        }
      },
    );
  };

  onPressBackground = () => {
    if (this.state.loading) {
      return;
    }

    this.setState({
      modalVisible: false,
      loading: false,
      success: false,
      queryingGas: false,
    });
  };

  _acceptOffer = () => {
    this.handleShowWalletConnectSignAgreeBid();
    return;

    WalletUtils.getCreateAuctionGasPrice()
      .then((res) => {
        this.setState({
          gasUsed: res,
          callFunc: 'acceptPrice',
          modalVisible: true,
        });
      })
      .catch((err) => {
        console.log('获取失败');
      });
  };

  _agreeOutSaleAuctionBid = () => {
    this.handleShowWalletConnectSignAgreeOutSaleBid();
    return;
    WalletUtils.getCreateAuctionGasPrice()
      .then((res) => {
        this.setState({
          gasUsed: res,
          callFunc: 'agreeOutSaleAuctionBid',
          modalVisible: true,
        });
      })
      .catch((err) => {
        console.log('获取失败');
      });
  };

  _approve = () => {
    this.handleShowWalletConnectSignApproveNft();
    return;

    this.setState({
      queryingGas: true,
    });

    WalletUtils.getRegisterNFTGasPrice()
      .then((res) => {
        this.setState({
          queryingGas: false,
          gasUsed: res,
          callFunc: 'approve',
          modalVisible: true,
        });
      })
      .catch((err) => {
        console.log('获取失败');
      });
  };

  _handlerView = () => {
    let {value, payCoin} = this.props.navigation.state.params.offer;
    let {fee} = this.props.navigation.state.params.auction;
    let {callFunc} = this.state;

    let alertText =
      callFunc !== 'approve'
        ? `Send a transaction to accept this bid. After the transaction is completed, NFT will be transferred to the bid address and you will receive ${Number(
            (value * (1 - fee)).toFixed(6),
          )} ${payCoin}`
        : 'Approve NFT Sell';

    return (
      <View style={{width: '100%'}}>
        <Text
          style={{
            fontWeight: 'bold',
            marginTop: 20,
            marginBottom: 20,
            color: '#6701F4',
          }}>
          {alertText}
        </Text>
        <Image
          style={{height: 1, width: '100%', marginBottom: 10}}
          source={require('../../assets/auction/line.png')}></Image>
        <View style={{width: '100%'}}>
          <View
            style={{
              flexDirection: 'row',
              justifyContent: 'space-between',
              width: '100%',
              marginTop: 0,
            }}>
            <Text style={{lineHeight: 30, color: '#6902F4'}}>
              Call Function
            </Text>
            <Text
              style={{
                fontWeight: 'bold',
                color: '#6902F4',
                lineHeight: 30,
              }}>
              {this.state.callFunc}
            </Text>
          </View>
        </View>
        <View style={{width: '100%', marginBottom: 10}}>
          <View
            style={{
              flexDirection: 'row',
              justifyContent: 'space-between',
              width: '100%',
              marginTop: 0,
            }}>
            <Text style={{lineHeight: 30, color: '#6902F4'}}>Gas Fee</Text>
            <Text
              style={{
                fontWeight: 'bold',
                color: '#6902F4',
                lineHeight: 30,
              }}>{`${this.state.gasUsed}${this.props.gasSymbol}`}</Text>
          </View>
        </View>
        <LinerBoardTextInput
          style={{
            width: '100%',
            padding: 0,
            height: 44,
          }}
          secureTextEntry={true}
          onChangeText={(text) => {
            this.setState({
              password: text,
            });
          }}
          placeholder="Your wallet password"></LinerBoardTextInput>
        <View
          style={{
            width: '100%',
            flexDirection: 'row',
            justifyContent: 'flex-end',
            marginBottom: 30,
          }}>
          <LinearBoardButton
            buttonStyle={{
              width: 100,
              height: 30,
              marginRight: 20,
            }}
            onPress={() => {
              this.setState({
                modalVisible: false,
              });
            }}
            text={'Cancel'}></LinearBoardButton>
          <LinearButton
            buttonStyle={{
              width: 100,
              height: 30,
            }}
            onPress={this.confirm}
            text={'Confirm'}></LinearButton>
        </View>
      </View>
    );
  };

  onPressWalletBackground = () => {
    this.setState({
      showWalletConnect: false,
    });
  };

  resultCall = (hash, err) => {
    if (err) {
      this.setState(
        {
          showWalletConnect: false,
        },
        () => {
          this._showAlert({content: err});
        },
      );
      return;
    }
    console.log('收到交易的HASH回调');
    console.log(hash);

    this.setState({
      showWalletConnect: false,
      modalVisible: true,
      loading: true,
    });

    WalletUtils.listenTx(hash)
      .then((res) => {
        console.log('交易已上链' + res);

        if (this.signinAgreeBid) {
          this.setState({
            success: true,
          });
          setTimeout(() => {
            this.setState(
              {
                modalVisible: false,
              },
              () => {
                this.props.navigation.state.params.refresh();
                this.props.navigation.goBack();
              },
            );
          }, 1000);
        } else if (this.signinApprove) {
          console.log(res);
          this.setState({
            success: true,
            approved: true,
          });
          setTimeout(() => {
            this.setState({
              modalVisible: false,
              success: false,
              loading: false,
            });
          }, 1 * 1000);
        } else {
          this.setState({
            success: true,
          });

          setTimeout(() => {
            this.setState(
              {
                modalVisible: false,
              },
              () => {
                this.props.navigation.state.params.refresh();
                this.props.navigation.goBack();
              },
            );
          }, 2000);
        }
      })
      .catch((err) => {
        console.log('交易失败');
        this.setState(
          {
            modalVisible: false,
            loading: false,
          },
          () => {
            this._showAlert({content: err?.message || err + ''});
          },
        );
      });
  };

  handleShowWalletConnectSignAgreeBid = async () => {
    //生成交易
    this._showLoading();
    try {
      this.signinAgreeBid = true;

      let {tokenId, nftAddress} = this.props.navigation.state.params.auction;

      let tx = await WalletUtils.getAcceptPriceTx(
        this.props.proxy.address,
        nftAddress,
        tokenId,
        this.props.userInfo.metamaskAddress,
      );
      console.log(tx);
      this._hideLoading();
      //跳转
      this.setState({
        showWalletConnect: true,
        tx,
      });
    } catch (err) {
      this._hideLoading();
      this._showAlert({content: err?.msg || err + ''});
    }
  };

  handleShowWalletConnectSignApproveNft = async () => {
    //生成交易
    this._showLoading();
    try {
      this.signinApprove = true;

      let {tokenId, nftAddress} = this.props.navigation.state.params.auction;
      let tx = await WalletUtils.getApproveNFTTx(
        nftAddress,
        this.props.proxy.address,
        tokenId,
        this.props.userInfo.metamaskAddress,
      );

      console.log(tx);
      this._hideLoading();
      //跳转
      this.setState({
        showWalletConnect: true,
        tx,
      });
    } catch (err) {
      this._hideLoading();
      this._showAlert({content: err?.msg || err + ''});
    }
  };

  handleShowWalletConnectSignAgreeOutSaleBid = async () => {
    //生成交易
    this._showLoading();
    try {
      this.signinAgreeBid = true;

      let {tokenId, nftAddress} = this.props.navigation.state.params.auction;

      let tx = await WalletUtils.getAgreeOutSaleAuctionBidTx(
        this.props.proxy.address,
        nftAddress,
        tokenId,
        this.props.userInfo.metamaskAddress,
      );

      console.log(tx);
      this._hideLoading();
      //跳转
      this.setState({
        showWalletConnect: true,
        tx,
      });
    } catch (err) {
      this._hideLoading();
      this._showAlert({content: err?.msg || err + ''});
    }
  };

  renderComponent = () => {
    let {offer, auction} = this.props.navigation.state.params;
    let {
      modalVisible,
      loading,
      success,
      approved,
      queryingGas,
      showWalletConnect,
      tx,
    } = this.state;

    let {payCoin, payCoinDecimal, value} = offer;

    let top =
      500 +
      Math.sqrt(
        Math.pow(500, 2) - Math.pow(LayoutConstants.WINDOW_WIDTH / 2, 2),
      );

    let isFromDogeswap = auction.from.indexOf('dogeswap') != -1;

    return (
      <View style={{flex: 1, backgroundColor: '#fff'}}>
        <NormalHeader
          navigation={this.props.navigation}
          text="Accept Offer"
          left={{
            icon: require('../../assets/common/common_back_white.png'),
            onPress: () => {
              Keyboard.dismiss();
              this.props.navigation.goBack();
            },
          }}
        />
        <View
          style={{
            padding: 20,
            flex: 1,
            alignItems: 'center',
          }}>
          <View
            style={{
              width: 1000,
              height: 1000,
              alignSelf: 'center',
              marginTop: -top,
              borderRadius: 500,
              backgroundColor: '#160231',
            }}></View>
          <Image
            style={{
              width: 90,
              height: 90,
              borderRadius: 10,
              alignSelf: 'center',
              marginTop: -30,
            }}
            source={{uri: auction.img}}></Image>
          <Text style={{fontWeight: 'bold', fontSize: 16, marginTop: 20}}>
            {auction.name}
          </Text>
          <View
            style={{
              flexDirection: 'row',
              marginTop: 10,
              alignItems: 'flex-end',
            }}>
            <Text
              style={{
                fontWeight: 'bold',
                fontSize: 40,
                color: '#7204F4',
              }}>
              {value}
            </Text>
            <Text
              style={{
                fontWeight: 'bold',
                fontSize: 20,
                color: '#7204F4',
                marginBottom: 5,
              }}>
              {payCoin}
            </Text>
          </View>
          {/* <Text
            style={{
              fontSize: 21,
              fontWeight: 'bold',
              color: '#A1A1A1',
            }}>{`($${offer.value})`}</Text> */}
          <View
            style={{width: '100%', alignItems: 'flex-start', marginTop: 20}}>
            <Text
              style={{
                fontSize: 18,
                fontWeight: 'bold',
                color: '#7204F4',
              }}>
              Fees
            </Text>
          </View>
          <View
            style={{
              width: '100%',
              flexDirection: 'row',
              justifyContent: 'space-between',
              marginTop: 10,
            }}>
            <Text
              style={{
                fontSize: 16,
              }}>
              To SignIn
            </Text>
            <Text
              style={{
                fontSize: 18,
                marginLeft: 10,
                color: '#7305F4',
              }}>
              {`${Number(
                subNumerString(
                  isFromDogeswap ? auction.fee * 100 * 0.5 : auction.fee * 100,
                  2,
                ),
              )}%`}
            </Text>
          </View>
          {isFromDogeswap ? (
            <View
              style={{
                width: '100%',
                flexDirection: 'row',
                justifyContent: 'space-between',
                marginTop: 10,
              }}>
              <Text
                style={{
                  fontSize: 16,
                }}>
                To DogeSwap
              </Text>
              <Text
                style={{
                  fontSize: 16,
                  marginLeft: 10,
                  color: '#7305F4',
                }}>
                {`${Number(subNumerString(auction.fee * 0.5 * 100, 4))}%`}
              </Text>
            </View>
          ) : null}
          <View
            style={{
              marginTop: 30,
              marginBottom: 30,
              height: 1,
              width: '100%',
              backgroundColor: 'rgba(200,200,200,1)',
            }}></View>
          <View
            style={{
              width: '100%',
              flexDirection: 'row',
              justifyContent: 'space-between',
            }}>
            <Text
              style={{
                fontSize: 18,
                fontWeight: 'bold',
                color: '#160231',
              }}>
              Total Earnings
            </Text>
            <View style={{flexDirection: 'row', alignItems: 'flex-end'}}>
              <Text
                style={{
                  fontSize: 24,
                  color: '#7305F4',
                }}>
                {`${Number((offer.value * (1 - auction.fee)).toFixed(6))}`}
              </Text>
              <Text
                style={{
                  fontSize: 14,
                  color: '#7305F4',
                  marginBottom: 4,
                  marginLeft: 4,
                }}>
                {payCoin}
              </Text>
            </View>
          </View>
        </View>
        {auction.status == 0 ? (
          <LinearBoardButton
            text="Accept"
            buttonStyle={{
              alignSelf: 'center',
              backgroundColor: '#FFCB26',
              width: 150,
              marginBottom: 50,
            }}
            onPress={this._acceptOffer}></LinearBoardButton>
        ) : (
          <View
            style={{
              flexDirection: 'row',
              justifyContent: 'center',
              alignItems: 'center',
              marginBottom: 70,
            }}>
            <LinearButton
              buttonStyle={{
                width: '40%',
                marginRight: 10,
              }}
              isDisabled={approved}
              loading={queryingGas}
              text={'Approve'}
              onPress={this._approve}
            />
            <Image
              style={{
                width: 30,
                height: 30,
                marginRight: 10,
                marginTop: 20,
                alignSelf: 'center',
              }}
              source={require('../../assets/auction/next_step.png')}
            />
            <LinearButton
              isDisabled={!approved}
              buttonStyle={{width: '40%'}}
              text={'Accept'}
              onPress={this._agreeOutSaleAuctionBid}
            />
          </View>
        )}
        <View
          style={{
            width: '100%',
            height: this.props.widgetLayout.show
              ? this.props.widgetLayout.height
              : 0,
            marginTop: 10,
          }}></View>
        <ModalHandler
          visible={modalVisible}
          loading={loading}
          success={success}
          handlerView={this._handlerView}
          onPressBackground={this.onPressBackground}
        />
        <WalletConnectModal
          visible={showWalletConnect}
          resultCall={this.resultCall}
          onPressBackground={this.onPressWalletBackground}
          tx={tx}></WalletConnectModal>
      </View>
    );
  };
}

const mapStateToProps = (state) => ({
  userInfo: state.User.userInfo,
  gasSymbol: state.Chain.gasSymbol,
  proxy: state.Chain.proxy,
  widgetLayout: state.Layout.widgetLayout,
});

const mapDispatchToProps = (dispatch) => ({});

export default connect(mapStateToProps, mapDispatchToProps)(Accept);
